package com.fs.warehouse.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.core.page.PageDomain;
import com.fs.common.core.pojo.Product;
import com.fs.common.core.pojo.SysUser;
import com.fs.common.core.vo.LoginUser;
import com.fs.procure.pojo.Insto;
import com.fs.procure.vo.InstoVo;
import com.fs.sale.service.InventoryService;
import com.fs.sale.vo.UpdateInventoryVo;
import com.fs.system.mapper.SysUserMapper;
import com.fs.system.util.SecurityUtils;
import com.fs.warehouse.mapper.*;
import com.fs.warehouse.pojo.*;
import com.fs.warehouse.service.WarehouseService;
import com.fs.warehouse.vo.DefectiveProductVo;
import com.fs.warehouse.vo.InventoryVo;
import com.fs.warehouse.vo.WarehousingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WarehouseServiceImpl implements WarehouseService {
    @Autowired
    private WhWarehouseMapper warehouseMapper;
    @Autowired
    private WhInvInventoryMapper invInventoryMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private WhInvInventoryDetailMapper invInventoryDetailMapper;
    @Autowired
    private WhWarehousingMapper warehousingMapper;
    @Autowired
    private WhDetailedMapper detailedMapper;
    @Autowired
    private WhDefectiveHandleApplicationMapper handleApplicationMapper;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private WhOutboundMapper outboundMapper;

    @Override
    public void designatedEmployeeInv(String inStoId, String userName) {
        //TODO:指定入库员工业务方法待完成
    }

    @Override
    public List<WhWarehouse> getAllWarehouse() {
        return warehouseMapper.selectList(null);
    }

    @Override
    public void initiateInventory(Integer warehouseId, Integer inventoryTakerId, Date inventoryTime, List<Product> products) {
        //创建库存盘点对象
        WhInvInventory invInventory = new WhInvInventory();
        invInventory.setWarehouseId(warehouseId);
        //根据用户名查询对应用户id

        invInventory.setInventoryTakerId(inventoryTakerId);
        //插入盘点人姓名
        SysUser sysUser = userMapper.selectUserById(Convert.toLong(inventoryTakerId));
        invInventory.setInventoryTakerName(sysUser.getUserName());
        //插入时间
        invInventory.setInventoryDate(inventoryTime);
        //插入仓库名
        WhWarehouse warehouse = warehouseMapper.selectById(warehouseId);
        invInventory.setWarehouseName(warehouse.getWarehouseName());
        //插入库存盘点
        invInventoryMapper.addInventory(invInventory);
        //往库存明细表插入数据
        WhInvInventoryDetail invInventoryDetail = null;

        for (Product p:products){
            invInventoryDetail = new WhInvInventoryDetail();
            invInventoryDetail.setInventoryId(Convert.toInt(invInventory.getInventoryId()));
            invInventoryDetail.setProductId(p.getProductId());
            invInventoryDetail.setProductName(p.getProductName());
            invInventoryDetailMapper.insert(invInventoryDetail);
        }

    }

    @Override
    public void generateWarehousing(WarehousingVo warehousingVo) {
//        WhWarehousing warehousing = voToWarehousing(warehousingVo);
//        //插入入库单
//        warehousingMapper.addWarehousing(warehousing);
//        //插入入库单数据
//        List<WhDetailed> list = warehousingVo.getWhDetailedList();
//        for(WhDetailed detailed:list) {
//            detailed.setWarehousingId(Convert.toInt(warehousing.getWarehousingId()));
//            detailedMapper.insert(detailed);
//        }
    }

    @Override
    public Page<WhWarehousing> selectWarehousingList(PageDomain pageDomain, WarehousingVo warehousingVo) {
        //把PageDomain 转换为 Page对象
//        Page<WhWarehousing> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
//        if(pageDomain.getIsAsc().equalsIgnoreCase("asc")){ //升序
//            page.addOrder(OrderItem.asc(pageDomain.getOrderByColumn()));
//        }else if(pageDomain.getIsAsc().equalsIgnoreCase("desc")){ //降序
//            page.addOrder(OrderItem.desc(pageDomain.getOrderByColumn()));
//        }
//
//        WhWarehousing warehousing = null;//voToWarehousing(warehousingVo)
//        List<WhWarehousing> warehousingList = warehousingMapper.selectWarehousingList(page, warehousing);
//        //TODO: 获取所有入库单任务待完成（商品数据）
//        //如果是普通员工查询，那么只显示普通员工负责的入库单
//        Long userId = SecurityUtils.getUserId();
//        String postName = userMapper.selectPostNameByUserId(userId);
//        List<WhWarehousing> matchedWarehousingList = new ArrayList<>();
//        if(postName.equals("普通员工")){
//            warehousingList.stream()
//                    .filter(w -> w.getUserId() == userId.intValue())
//                    .forEach(matchedWarehousingList::add);
//            page.setRecords(matchedWarehousingList);
//        }else {
//            page.setRecords(warehousingList);
//        }
//        return page;
        return null;
    }

    @Override
    public Page<Insto> selectWarehousingApplication(PageDomain pageDomain, InstoVo instoVo) {
        //TODO: 获取所有入库申请任务待完成
        return null;
    }

    @Override
    public Page<WhInvInventory> selectInventory(PageDomain pageDomain, InventoryVo inventoryVo) {

        //把PageDomain 转换为 Page对象
        Page<WhInvInventory> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        if(pageDomain.getIsAsc().equalsIgnoreCase("asc")){ //升序
            page.addOrder(OrderItem.asc(pageDomain.getOrderByColumn()));
        }else if(pageDomain.getIsAsc().equalsIgnoreCase("desc")){ //降序
            page.addOrder(OrderItem.desc(pageDomain.getOrderByColumn()));
        }
        WhInvInventory inventory =  new WhInvInventory();

        if(Objects.nonNull(inventoryVo.getWarehouseId())){
            inventory.setWarehouseId(inventoryVo.getWarehouseId());
        }
        inventory.setInventoryDate(inventoryVo.getInventoryTime());

        if(Objects.nonNull(inventoryVo.getInventoryTaKerId())){
            inventory.setInventoryTakerId(inventoryVo.getInventoryTaKerId());
        }
        List<WhInvInventory> inventoryList = invInventoryMapper.selectInventoryList(page, inventory);
        //如果是普通员工查询，那么只显示普通员工负责的入库单
        String username = SecurityUtils.getUsername();
        Long userId = SecurityUtils.getUserId();
        String postName = userMapper.selectPostNameByUserId(userId);
        List<WhInvInventory> matchedInventoryList = new ArrayList<>();
        if(postName.equals("普通员工")){
            inventoryList.stream()
                    .filter(w -> w.getInventoryTakerName().equals(username))
                    .forEach(matchedInventoryList::add);
            page.setRecords(matchedInventoryList);
        }else {
            page.setRecords(inventoryList);
        }
        return page;
    }

    @Override
    public WhInvInventory updateStatus(WhInvInventory invInventory) {
        WhInvInventory newInvInventory = new WhInvInventory();
        if(Objects.nonNull(invInventory.getInventoryId()))
            newInvInventory.setInventoryId(invInventory.getInventoryId());
        if(Objects.nonNull(invInventory.getApprovalStatus()))
            newInvInventory.setApprovalStatus(invInventory.getApprovalStatus());
        if(Objects.nonNull(invInventory.getCountResult()))
            newInvInventory.setCountResult(invInventory.getCountResult());
        if(Objects.nonNull(invInventory.getInventoryNotes()))
            newInvInventory.setInventoryNotes(invInventory.getInventoryNotes());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        newInvInventory.setApproverId(loginUser.getUserId().intValue());
        newInvInventory.setApproverName(loginUser.getUsername());
        newInvInventory.setApprovalDate(Convert.toLocalDateTime(new Date()));
        int update = invInventoryMapper.update(newInvInventory, new LambdaQueryWrapper<WhInvInventory>().eq(WhInvInventory::getInventoryId, invInventory.getInventoryId()));
        return newInvInventory;
    }

    @Override
    public WhInvInventory fillInventoryDetail(List<WhInvInventoryDetail> invInventoryDetails) {
        WhInvInventory invInventory = invInventoryMapper.selectOne(new LambdaQueryWrapper<WhInvInventory>().eq(WhInvInventory::getInventoryId, invInventoryDetails.get(0).getInventoryId()));
        invInventoryDetails.forEach(detail ->{
            invInventoryDetailMapper.updateById(detail);
        });

        return invInventory;
    }

    @Override
    public void submitDefectiveApplication(List<WhDefectiveHandleApplication> defectiveHandle) {

        Long userId = SecurityUtils.getUserId();
        defectiveHandle.forEach(d ->{
            d.setApplicationId(userId.intValue());
            handleApplicationMapper.insert(d);
        });
    }

    @Override
    public Page<DefectiveProductVo> selectDefectiveApplication(PageDomain pageDomain,DefectiveProductVo defectiveProductVo) {
        Page<DefectiveProductVo> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        if(pageDomain.getIsAsc().equalsIgnoreCase("asc")){ //升序
            page.addOrder(OrderItem.asc(pageDomain.getOrderByColumn()));
        }else if(pageDomain.getIsAsc().equalsIgnoreCase("desc")){ //降序
            page.addOrder(OrderItem.desc(pageDomain.getOrderByColumn()));
        }
        return  handleApplicationMapper.selectAll(page,defectiveProductVo);
    }

    @Override
    public void updateDefectiveStatus(DefectiveProductVo defectiveProductVo) {
        WhDefectiveHandleApplication handleApplication = new WhDefectiveHandleApplication();
        handleApplication.setDHId(defectiveProductVo.getDefectiveApplicationId());
        handleApplication.setApplicationStatus(defectiveProductVo.getApplicationStatus());
        handleApplicationMapper.updateById(handleApplication);
        if(defectiveProductVo.getApplicationStatus().equals("审核通过")){
            UpdateInventoryVo updateInventoryVo = new UpdateInventoryVo();
            updateInventoryVo.setVariantId(defectiveProductVo.getVariantId());
            updateInventoryVo.setReduceNum(defectiveProductVo.getHandleNumber());
            inventoryService.updateInventory(updateInventoryVo);
        }
    }

    @Override
    public void generateOutbound(WhOutbound outbound) {
        outbound.setOutbounder(SecurityUtils.getUsername());
        //TODO：出库明细添加
        WhDetailed detailed = null;
        outbound.getDetailedList().forEach(p->{
        });
        outboundMapper.insert(outbound);
    }

    @Override
    public List<WarehousingVo> selectWarehousing() {
        List<WarehousingVo> obdDeliveryVoList= warehousingMapper.query();
        for(WarehousingVo obdDeliveryVo:obdDeliveryVoList){
            if(obdDeliveryVo.getUserId()!=null){
                obdDeliveryVo.setUserId(userMapper.selectUserById(obdDeliveryVo.getUserId().longValue()).getUserId().intValue());
            }
        }
        String post = userMapper.selectPostNameByUserId(SecurityUtils.getUserId());
        if(post.equals("普通员工")){
            int userId = SecurityUtils.getUserId().intValue();
            List<WarehousingVo> deliveredItems = obdDeliveryVoList.stream()
                    .filter(item -> userId == item.getUserId() )
                    .collect(Collectors.toList());
            return deliveredItems;
        }

        return obdDeliveryVoList;
    }



}
